use anyhow::Ok;
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};

use crate::{entity, model::App};

pub async fn find_by_id(db: &DatabaseConnection, id: i64) -> anyhow::Result<Option<App>> {
    let app = entity::app::Entity::find_by_id(id)
        .one(db)
        .await?
        .map(|entity| App::from(entity));

    Ok(app)
}

pub async fn find_by_access_key_id(
    db: &DatabaseConnection,
    access_key_id: &str,
) -> anyhow::Result<Option<App>> {
    let app = entity::app::Entity::find()
        .filter(entity::app::Column::AccessKeyId.eq(access_key_id))
        .one(db)
        .await?
        .map(|entity| App::from(entity));

    Ok(app)
}
